package com.xvyy.tingshu.album.receiver;


import com.alibaba.fastjson.JSONObject;
import com.xvyy.tingshu.album.service.MqOpsService;
import com.xvyy.tingshu.common.execption.TsException;
import com.xvyy.tingshu.common.rabbit.constant.MqConst;
import com.xvyy.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * ClassName: AlbumInfoReceiver
 * Package: com.xvyy.tingshu.album.receiver
 *
 * @Description:
 * @Author: xvyy
 * @Create: 2025/2/5 - 20:07
 * @Version: v1.0
 */
@Component
@Slf4j
public class AlbumInfoReceiver {

    @Autowired
    private MqOpsService mqOpsService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 监听专辑和声音的统计信息更新
     * @param content
     * @param message
     * @param channel
     */
    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE, durable = "true", exclusive = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK),
            key = MqConst.ROUTING_TRACK_STAT_UPDATE))
    @SneakyThrows   // 可以绕开编译期间的异常 等运行时发现异常才抛出
    public void listenAlbumAndTrackStatNumUpdate(String content, Message message, Channel channel) {
        // 1.获取消息，进行判断
        if (StringUtils.isEmpty(content)) {
            return;
        }
        // 2.消息转换
        TrackStatMqVo trackStatMqVo = JSONObject.parseObject(content, TrackStatMqVo.class);
        // 3.消费消息
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            mqOpsService.listenAlbumAndTrackStatNumUpdate(trackStatMqVo);
            // 4.手动应答
            channel.basicAck(deliveryTag, false);
        } catch (TsException e) {
            // 重试 消息继续能够被消费者消费
            String retryMsgKey = "retry:msg:" + trackStatMqVo.getBusinessNo();
            Long increment = stringRedisTemplate.opsForValue().increment(retryMsgKey);
            if (increment >= 3) {
                log.error("消息重试了{}次，异常原因：{}，请人工排查", increment, e.getMessage());
                channel.basicNack(deliveryTag, false, false);  // 删除掉
            } else {
                log.error("消息重试了{}次", increment);
                channel.basicNack(deliveryTag, false, true);
            }
        } catch (Exception e) {
            log.error("手动应答期间，网络出现了抖动，但是业务已经被成功执行过，消息直接丢掉");
            log.error("异常原因：{}", e.getMessage());
            channel.basicNack(deliveryTag, false, false);
        }
    }

    /**
     * 更新MySQL中的购买量
     *
     * @param orderNo
     * @param message
     * @param channel
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ALBUM_STAT_UPDATE, durable = "true", exclusive = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM),
            key = MqConst.ROUTING_ALBUM_STAT_UPDATE))
    @SneakyThrows
    public void listenAlbumAndBuyNumUpdate(String orderNo, Message message, Channel channel) {
        // 1. 获取消息，进行判断
        if (StringUtils.isEmpty(orderNo)) {
            return;
        }
        // 2. 消费消息
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            // 3. 更新MySQL中的购买量
            mqOpsService.albumAndBuyNumUpdate(orderNo);
            // 4. 手动应答
            channel.basicAck(deliveryTag, false);
        } catch (TsException e) {
            // 5. 重试 消息继续能够被消费者消费
            String retryMsgKey = "retry:msg:" + orderNo;
            Long increment = stringRedisTemplate.opsForValue().increment(retryMsgKey);
            if (increment >= 3) {
                log.error("消息重试了{}次，异常原因：{}，请人工排查", increment, e.getMessage());
                channel.basicNack(deliveryTag, false, false);  // 删除掉
            } else {
                log.error("消息重试了{}次", increment);
                channel.basicNack(deliveryTag, false, true);
            }
        } catch (Exception e) {
            log.error("手动应答期间，网络出现了抖动，但是业务已经被成功执行过，消息直接丢掉");
            log.error("异常原因：{}", e.getMessage());
            channel.basicNack(deliveryTag, false, false);
        }
    }


}